package com.xxh.blog.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxh.blog.dao.UserCollectionDao;
import com.xxh.blog.dao.UserDao;
import com.xxh.blog.dao.UserMessageDao;
import com.xxh.blog.entity.*;
import com.xxh.blog.entity.vo.UserMessageVo;
import com.xxh.blog.service.CommentService;
import com.xxh.blog.service.essayService;
import com.xxh.blog.shiro.AccountProfile;
import com.xxh.blog.utils.Result;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
public class userController {

    @Autowired
    UserDao userDao;

    @Resource
    com.xxh.blog.service.essayService essayService;

    @Resource
    CommentService commentService;

    @Autowired
    UserMessageDao userMessageDao;


    @Autowired
    UserCollectionDao userCollectionDao;

    /**
     * 用户主页视图返回
     * @param model
     * @return
     */
    @RequestMapping("/user/home")
    public String userhome(Model model){

        AccountProfile Curuser=(AccountProfile)SecurityUtils.getSubject().getPrincipal();
        //获取用户基本信息
        User user = userDao.selectById(Curuser.getId());

        //获取用户发布的文章
        List<Essay> user_articles = essayService.list(new QueryWrapper<Essay>().eq("user_id", user.getId()));

        //获取用户的回复
        List<Comment> user_comment = commentService.list(new QueryWrapper<Comment>().eq("user_id", user.getId()));


        model.addAttribute("userArticles",user_articles);
        model.addAttribute("userComment",user_comment);
        model.addAttribute("userHomeInfo",user);

        return "user/home";
    }

    @RequestMapping("/user/set")
    public String userSet(Model model){

        AccountProfile Curuser=(AccountProfile)SecurityUtils.getSubject().getPrincipal();
        //获取用户基本信息
        User user = userDao.selectById(Curuser.getId());

        model.addAttribute("user",user);

        return "/user/set";
    }


    /**
     * 更新用户信息
     * @param user
     * @return
     */
    @ResponseBody
    @PostMapping("/user/set")
    public Result UserInfoAlter(User user){

        if(StrUtil.isEmpty(user.getUsername())){
            return Result.error("昵称不能为空").put("status",0);
        }
        Integer count = userDao.selectCount(new QueryWrapper<User>().eq("username", user.getUsername()).ne("email",user.getEmail()));
        if(count==1){
            return Result.error("昵称重复，修改失败").put("status",0);
        }
        User tempUser = userDao.selectOne(new QueryWrapper<User>().eq("email", user.getEmail()));
        tempUser.setSign(user.getSign());
        tempUser.setUsername(user.getUsername());
        userDao.updateByPrimaryKey(tempUser);
        AccountProfile Curuser=(AccountProfile)SecurityUtils.getSubject().getPrincipal();

        SecurityUtils.getSubject().getSession().setAttribute("profile",Curuser);
        Curuser.setUsername(user.getUsername());

        SecurityUtils.getSubject().getPrincipal();
        return Result.ok("请求完成").put("status",0);
    }

    /**
     * 用户中心
     * @return
     */

    @RequestMapping("/user/index")
    public String UserIndex(){

        return "user/index";
    }

    /**
     * 用户查看自己的消息
     * @return
     */
    @RequestMapping("/user/message")
    public String UserMessage(HttpServletRequest request,Model model){
        AccountProfile Curuser=(AccountProfile)SecurityUtils.getSubject().getPrincipal();
        Integer curpage = request.getParameter("curpage") == null ? 1 : Integer.parseInt(request.getParameter("curpage"));
        IPage<UserMessageVo> paging = userMessageDao.paging(new Page(curpage, 2), new QueryWrapper<UserMessageVo>().eq("to_user_id", Curuser.getId()));

        //设置用户消息为已读(我实在太懒了不好意思)
        List<Long> ids = paging.getRecords().stream().map(userMessageVo -> {
            return userMessageVo.getId();
        }).collect(Collectors.toList());
        for(Long id :ids){
            userMessageDao.upDateToRead(new QueryWrapper<UserMessage>().eq("id",id));
        }
        model.addAttribute("mymessage",paging);
        return "/user/message";
    }

    @RequestMapping("/user/public")
    @ResponseBody
    public Result userPublic(HttpServletRequest request){
        AccountProfile Curuser=(AccountProfile)SecurityUtils.getSubject().getPrincipal();
        Integer curpage = request.getParameter("page") == null ? 1 : Integer.parseInt(request.getParameter("page"));
        Page<Essay> Ipage = essayService.page(new Page<>(curpage, 2), new QueryWrapper<Essay>().eq("user_id", Curuser.getId()));
        return Result.ok().put("data",Ipage);
    }

    /**
     * 文章是否被用户收藏
     * @param cid 文章ID
     * @return
     */
    @PostMapping("/collection/find")
    @ResponseBody
    public Result collectionFind(long cid){

        //获取当前登录的用户
        AccountProfile Curuser=(AccountProfile)SecurityUtils.getSubject().getPrincipal();
        Long uid = Curuser.getId();
        Integer count = userCollectionDao.selectCount(new QueryWrapper<UserCollection>().eq("post_id", cid).eq("user_id",uid));
        Map<String, Object> map = new HashMap<>();
        map.put("collection",count>0);
        return Result.ok().put("data",map);
    }

    /**
     * 添加收藏
     * @param cid 文章ID
     * @return
     */
    @ResponseBody
    @PostMapping("/collection/add")
    public Result collectionAdd(long cid){
        //获取当前登录的用户
        AccountProfile Curuser=(AccountProfile)SecurityUtils.getSubject().getPrincipal();
        Long uid = Curuser.getId();
        //新增一条记录

        //文章作者
        Long postUserId = essayService.getById(cid).getUserId();
        UserCollection collection = new UserCollection();
        collection.setPostId(cid);
        collection.setPostUserId(postUserId);
        collection.setCreated(new Date());
        collection.setModified(new Date());
        collection.setUserId(uid);
        userCollectionDao.insert(collection);

        return Result.ok();
    }


    /**
     * 取消收藏
     * @param cid 文章ID
     * @return
     */

    @ResponseBody
    @PostMapping("/collection/remove")
    public Result collectionRemove(long cid){
        //获取当前登录的用户
        AccountProfile Curuser=(AccountProfile)SecurityUtils.getSubject().getPrincipal();
        Long uid = Curuser.getId();

        UserCollection collection = userCollectionDao.selectOne(new QueryWrapper<UserCollection>().eq("post_id", cid).eq("user_id", uid));
        userCollectionDao.deleteByPrimaryKey(collection.getId());
        return Result.ok();
    }



}
